package com.example.sunny.service.network.location

import android.content.Context
import android.util.Log
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.MyLocationData
import com.example.sunny.pojo.location.MyLocation

object LocationService {

    fun initLocation(context: Context, listener:MyLocationListener.LocationCallback): LocationClient {
        val option = LocationClientOption()
        option.apply {
            openGps = true
            coorType = "bd09ll"
            scanSpan = 1000 * 60 * 5
            setIsNeedAddress(true)
            setIsNeedLocationDescribe(true)
        }
        val locationClient = LocationClient(context)
        val locationListener = MyLocationListener(listener)

        return locationClient.apply {
            locationClient.locOption = option

            //注册LocationListener监听器

            locationClient.registerLocationListener(locationListener)

            locationClient.start()
        }

    }

    class MyLocationListener(private val locationListener: LocationCallback): BDAbstractLocationListener() {

        override fun onReceiveLocation(location: BDLocation?) {
            if (location!=null){
                val data = MyLocationData.Builder()
                    .accuracy(location.radius)
                    .direction(location.direction)
                    .latitude(location.latitude)
                    .longitude(location.longitude)
                    .build()

                Log.d("MyLocationListener","location.longitude=${location.longitude}")
                Log.d("MyLocationListener","location.latitude=${location.latitude}")
                Log.d("MyLocationListener","location.city=${location.city}")
                Log.d("MyLocationListener","location.street=${location.street}")
                Log.d("MyLocationListener","locationDescribe=${location.locationDescribe}")

                location.apply {
                    val myLocation = MyLocation(longitude,latitude,city,street,locationDescribe,radius,direction)
                    locationListener.getLocation(myLocation)
                }
            }
        }

        interface LocationCallback{
            fun getLocation(myLocation: MyLocation)
        }
    }
}